package com.itheima.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.entity.Result;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import com.itheima.utils.POIUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/ordersetting")
public class OrderSettingController {

    @Reference
    OrderSettingService orderSettingService;

    @RequestMapping("/editNumberByDate")
    public Result editNumberByDate(@RequestBody OrderSetting orderSetting){
         orderSettingService.editNumberByDate(orderSetting);
            return  Result.success("");
    }


    private boolean isNotEmpty(Object o){
        if(null == o){
            return false;
        }
        if(o instanceof  String){
            String o1 = (String) o;
            if(o1.equals("") || o1.equals(" ")){
                return false;
            }
        }
        return true;
    }

    @RequestMapping("/upload")
    public Result upload(MultipartFile excelFile ) throws IOException {
        //        使用poiutil读取Excel 返回一个list list里面装的是一个一个数组
        List<String[]> dataList = POIUtils.readExcel(excelFile);
        //把dataList转成List<OrderSetting>
        List<OrderSetting> orderSettings = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(dataList)){
            for (String[] array : dataList) {
                if(array.length != 2){//数据一定要完整
                    continue;
                }
                String dateStr = array[0];//yyyy/MM/dd
                String numberStr = array[1];
                if(isNotEmpty(dateStr) && isNotEmpty(numberStr)){
                    OrderSetting orderSetting = new OrderSetting();
                    orderSetting.setOrderDate(DateUtil.parse(dateStr,"yyyy/MM/dd"));
                    orderSetting.setNumber(Integer.valueOf(numberStr));

                    orderSettings.add(orderSetting);
                }

            }
        }
        orderSettingService.setNumberByDateBatch(orderSettings);

        return Result.success("");
    }



    @RequestMapping("/getOrderSettingByMonth")
    public Result  getOrderSettingByMonth(String date){
     List<Map>  map= orderSettingService.getOrderSettingByMonth(date);
        return  Result.success("",map);
    }


}
